"use client";
import { useState, useEffect } from "react";
import { Form, Input, Button, Card, Typography } from "antd";
import { UserOutlined, LockOutlined, LoginOutlined } from "@ant-design/icons";
import { adminAPI } from "@/lib/api";
import { useMessage } from "@/hooks/useMessage";

const { Title, Text } = Typography;

interface UserInfo {
  id: number;
  username: string;
  email: string;
  roles: string[];
}

export default function AdminLogin() {
  const message = useMessage();
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [captchaId, setCaptchaId] = useState<string>("");
  const [captchaSvg, setCaptchaSvg] = useState<string>("");
  const [, setCaptchaLoading] = useState(false);
  const [loginStatus, setLoginStatus] = useState<{
    isLocked: boolean;
    remainingTime: number;
    failureCount: number;
    maxAttempts: number;
  }>({
    isLocked: false,
    remainingTime: 0,
    failureCount: 0,
    maxAttempts: 10,
  });

  // 获取登录状态
  const getLoginStatus = async () => {
    try {
      const response = await adminAPI.getLoginStatus();
      if (response.success) {
        setLoginStatus(response.data);
        if (response.data.isLocked) {
          message.warning(`IP已被锁定，请在${response.data.remainingTime}分钟后再试`);
        }
      }
    } catch (error) {
      console.error("获取登录状态失败:", error);
    }
  };

  // 获取验证码
  const getCaptcha = async () => {
    console.log("🔄 开始获取验证码...");
    setCaptchaLoading(true);
    try {
      const response = await adminAPI.getCaptcha();
      console.log("✅ 验证码API响应:", response);
      if (response.success) {
        setCaptchaId(response.captchaId);
        setCaptchaSvg(response.captchaSvg);
        console.log("✅ 验证码设置成功:", { captchaId: response.captchaId, svgLength: response.captchaSvg.length });
      } else {
        console.error("❌ 验证码API返回失败:", response);
        message.error("获取验证码失败");
      }
    } catch (error) {
      console.error("❌ 获取验证码失败:", error);
      message.error("获取验证码失败");
    } finally {
      setCaptchaLoading(false);
      console.log("🔄 验证码获取流程结束");
    }
  };

  // 页面加载时获取验证码和登录状态
  useEffect(() => {
    console.log("📱 页面加载，开始初始化...");
    getCaptcha();
    getLoginStatus();
  }, []);

  // 添加状态变化监听
  useEffect(() => {
    console.log("🎯 验证码状态更新:", { captchaId, captchaSvgLength: captchaSvg.length });
  }, [captchaId, captchaSvg]);

  const handleLogin = async (values: { username: string; password: string; captchaCode: string }) => {
    // 检查是否被锁定
    if (loginStatus.isLocked) {
      message.error(`IP已被锁定，请在${loginStatus.remainingTime}分钟后再试`);
      return;
    }

    setLoading(true);
    try {
      const loginData = {
        username: values.username,
        password: values.password,
        captchaId,
        captchaCode: values.captchaCode,
      };

      const data = await adminAPI.login(loginData);
      console.log("✅ 登录API响应:", data);

      if (data.success) {
        // 后端现在设置了安全的HttpOnly cookie
        // 客户端不再需要手动管理token

        message.success("登录成功，正在跳转...");
        // 延迟跳转，让用户看到提示信息
        const userInfo: UserInfo = data.user as UserInfo;
        localStorage.setItem("userInfo", JSON.stringify(userInfo)); // 这一行必须加回来
        const roles: string[] = userInfo?.roles || [];
        setTimeout(() => {
          if (roles.includes("editor")) {
            window.location.href = "/admin/articles";
          } else {
            window.location.href = "/admin/dashboard";
          }
        }, 10);
      } else {
        // 由axios拦截器处理了大部分错误，这里处理业务逻辑上的失败
        message.error(data.message || "登录失败，请检查您的凭证");
        // 重新获取验证码和登录状态
        getCaptcha();
        getLoginStatus();
      }
    } catch (error: unknown) {
      console.error("登录请求失败:", error);
      // 处理axios拦截器返回的错误格式
      let errorMessage = "网络错误或服务器异常，请稍后重试";
      if (error && typeof error === 'object') {
        const errorObj = error as { message?: string; error?: string };
        errorMessage = errorObj.message || errorObj.error || errorMessage;
      } else if (typeof error === 'string') {
        errorMessage = error;
      }
      message.error(errorMessage);
      // 重新获取验证码和登录状态
      getCaptcha();
      getLoginStatus();
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      style={{
        minHeight: "100vh",
        background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "20px",
      }}
    >
      <Card
        style={{
          width: "100%",
          maxWidth: 400,
          boxShadow: "0 8px 32px rgba(0, 0, 0, 0.1)",
          borderRadius: "12px",
        }}
      >
        <div style={{ textAlign: "center", marginBottom: "32px" }}>
          <Title level={2} style={{ marginBottom: "8px", color: "#1890ff" }}>
            AI产品之家
          </Title>
          <Text type='secondary'>后台管理系统</Text>
        </div>

        <Form form={form} name='admin_login' onFinish={handleLogin} autoComplete='off' size='large'>
          {/* 安全提示 */}
          {(loginStatus.failureCount > 0 || loginStatus.isLocked) && (
            <div
              style={{
                marginBottom: "16px",
                padding: "12px",
                backgroundColor: loginStatus.isLocked ? "#fff2f0" : "#fffbe6",
                border: `1px solid ${loginStatus.isLocked ? "#ffccc7" : "#ffe58f"}`,
                borderRadius: "6px",
                fontSize: "14px",
              }}
            >
              {loginStatus.isLocked ? (
                <div style={{ color: "#cf1322" }}>🔒 IP已被锁定，剩余时间：{loginStatus.remainingTime}分钟</div>
              ) : (
                <div style={{ color: "#d46b08" }}>
                  ⚠️ 登录失败{loginStatus.failureCount}次，还有{loginStatus.maxAttempts - loginStatus.failureCount}次机会
                </div>
              )}
            </div>
          )}

          <Form.Item name='username' rules={[{ required: true, message: "请输入用户名" }]}>
            <Input prefix={<UserOutlined />} placeholder='请输入用户名' style={{ borderRadius: "8px" }} />
          </Form.Item>

          <Form.Item name='password' rules={[{ required: true, message: "请输入密码" }]}>
            <Input.Password prefix={<LockOutlined />} placeholder='请输入密码' style={{ borderRadius: "8px" }} />
          </Form.Item>

          <Form.Item name='captchaCode' rules={[{ required: true, message: "请输入验证码" }]}>
            <div style={{ display: "flex", alignItems: "center", gap: "8px", marginTop: "10px" }}>
              {/* 验证码图片 */}
              {captchaSvg && (
                <div
                  dangerouslySetInnerHTML={{ __html: captchaSvg }}
                  style={{
                    display: "inline-block",
                    border: "1px solid #d9d9d9",
                    borderRadius: "4px",
                    cursor: "pointer",
                    width: "auto",
                    height: "auto",
                    verticalAlign: "middle",
                    userSelect: "none",
                  }}
                  onClick={getCaptcha}
                  title='点击刷新验证码'
                />
              )}
              <Input placeholder='请输入验证码' style={{ borderRadius: "8px", height: "40px", flex: 1 }} />
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type='primary'
              htmlType='submit'
              loading={loading}
              disabled={loginStatus.isLocked}
              icon={<LoginOutlined />}
              style={{
                width: "100%",
                height: "48px",
                borderRadius: "8px",
                fontSize: "16px",
              }}
            >
              {loading ? "登录中..." : loginStatus.isLocked ? `锁定中(${loginStatus.remainingTime}分钟)` : "登录"}
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
